package config

import (
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
)

type Config struct {
}

func NewConfigStruct() *Config {
	return &Config{}
}

type LoggingStruct struct {
	OpenstackLoggingStruct OpenstackLoggingStruct `yaml:"loggin"`
}

type OpenstackLoggingStruct struct {
	OpenstackLogin OpenstackLogin `yaml:"openstack"`
}

type OpenstackLogin struct {
	Username   string `yaml:"username"`
	Password   string `yaml:"password"`
	Endpoint   string `yaml:"endpoint"`
	TenantName string `yaml:"tenant-name"`
	TenantID   string `yaml:"tenant-id"`
	Domain     string `yaml:"domain"`
	Region     string `yaml:"region"`
}

func (yam *Config) Load(filename string, v *LoggingStruct) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		panic(err.Error())
	}
	err = yaml.Unmarshal(data, v)
	if err != nil {
		panic(err.Error())
	}
}

func GetOpenstackConfig() OpenstackLogin {
	config := getLoginConfig()
	return config.OpenstackLoggingStruct.OpenstackLogin
}

func getLoginConfig() (v LoggingStruct) {
	conf := NewConfigStruct()
	configFile := "/etc/config.yml"
	_, err := os.Stat(configFile)
	if err != nil {
		configFile = "config/config.yml"
		_, err := os.Stat(configFile)
		if err != nil {
			panic(err)
		}
	}
	conf.Load(configFile, &v)
	val, ex := os.LookupEnv("OPENSTACK_PASSWORD")
	if ex == true {
		v.OpenstackLoggingStruct.OpenstackLogin.Password = val
	}
	val, ex = os.LookupEnv("OPENSTACK_ENDPOINT")
	if ex == true {
		v.OpenstackLoggingStruct.OpenstackLogin.Endpoint = val
	}
	return v
}
